import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { accountingApi } from "@/services/accountingService";
import type {
  TransactionResponse,
  TransactionCreate,
  TransactionUpdate,
  TransactionListParams,
  CategoryResponse,
  CategoryCreate,
  CategoryUpdate,
  AccountResponse,
  AccountCreate,
  AccountUpdate,
  AccountListParams,
  ProjectResponse,
  ProjectCreate,
  ProjectUpdate,
  TransactionSummary,
  StatisticsParams,
} from "@/types/accounting";

export const useAccountingStore = defineStore("accounting", () => {
  // 状态
  const transactions = ref<TransactionResponse[]>([]);
  const categories = ref<CategoryResponse[]>([]);
  const accounts = ref<AccountResponse[]>([]);
  const projects = ref<ProjectResponse[]>([]);
  const statistics = ref<TransactionSummary>({
    total_income: "0",
    total_expense: "0",
    total_transfer: "0",
    net_income: "0",
    transaction_count: 0,
  });
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 计算属性
  const incomeTransactions = computed(() =>
    transactions.value.filter((t) => t.transaction_type === "income"),
  );

  const expenseTransactions = computed(() =>
    transactions.value.filter((t) => t.transaction_type === "expense"),
  );

  const transferTransactions = computed(() =>
    transactions.value.filter((t) => t.transaction_type === "transfer"),
  );

  // Note: Backend doesn't include type field in CategoryResponse
  // const incomeCategories = computed(() =>
  //   categories.value.filter(c => c.type === 'income')
  // )

  // const expenseCategories = computed(() =>
  //   categories.value.filter(c => c.type === 'expense')
  // )

  const activeAccounts = computed(() =>
    accounts.value.filter((a) => a.is_active),
  );

  const activeProjects = computed(() =>
    projects.value.filter((p) => p.is_active),
  );

  const totalBalance = computed(() =>
    accounts.value.reduce(
      (sum, account) => sum + parseFloat(account.balance),
      0,
    ),
  );

  // 交易相关方法
  async function fetchTransactions(params?: TransactionListParams) {
    try {
      loading.value = true;
      error.value = null;
      const response = await accountingApi.transactions.getTransactions(params);
      transactions.value = response.transactions;
      return response;
    } catch (err) {
      console.error("获取交易记录失败:", err);
      error.value = "获取交易记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchTransaction(transactionId: number) {
    try {
      loading.value = true;
      error.value = null;
      return await accountingApi.transactions.getTransaction(transactionId);
    } catch (err) {
      console.error("获取交易详情失败:", err);
      error.value = "获取交易详情失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createTransaction(transactionData: TransactionCreate) {
    try {
      loading.value = true;
      error.value = null;
      const newTransaction =
        await accountingApi.transactions.createTransaction(transactionData);
      transactions.value.unshift(newTransaction);
      await fetchStatistics(); // 更新统计
      return newTransaction;
    } catch (err) {
      console.error("创建交易记录失败:", err);
      error.value = "创建交易记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateTransaction(
    transactionId: number,
    transactionData: TransactionUpdate,
  ) {
    try {
      loading.value = true;
      error.value = null;
      const updatedTransaction =
        await accountingApi.transactions.updateTransaction(
          transactionId,
          transactionData,
        );
      const index = transactions.value.findIndex((t) => t.id === transactionId);
      if (index !== -1) {
        transactions.value[index] = updatedTransaction;
      }
      await fetchStatistics(); // 更新统计
      return updatedTransaction;
    } catch (err) {
      console.error("更新交易记录失败:", err);
      error.value = "更新交易记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function deleteTransaction(transactionId: number) {
    try {
      loading.value = true;
      error.value = null;
      await accountingApi.transactions.deleteTransaction(transactionId);
      transactions.value = transactions.value.filter(
        (t) => t.id !== transactionId,
      );
      await fetchStatistics(); // 更新统计
    } catch (err) {
      console.error("删除交易记录失败:", err);
      error.value = "删除交易记录失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 分类相关方法
  async function fetchCategories(params?: {
    parent_id?: number | null;
    skip?: number;
    limit?: number;
  }) {
    try {
      loading.value = true;
      error.value = null;
      categories.value =
        await accountingApi.categories.getAllCategories(params);
      return categories.value;
    } catch (err) {
      console.error("获取分类列表失败:", err);
      error.value = "获取分类列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchCategory(categoryId: number) {
    try {
      loading.value = true;
      error.value = null;
      return await accountingApi.categories.getCategory(categoryId);
    } catch (err) {
      console.error("获取分类详情失败:", err);
      error.value = "获取分类详情失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createCategory(categoryData: CategoryCreate) {
    try {
      loading.value = true;
      error.value = null;
      const newCategory =
        await accountingApi.categories.createCategory(categoryData);
      categories.value.push(newCategory);
      return newCategory;
    } catch (err) {
      console.error("创建分类失败:", err);
      error.value = "创建分类失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateCategory(
    categoryId: number,
    categoryData: CategoryUpdate,
  ) {
    try {
      loading.value = true;
      error.value = null;
      const updatedCategory = await accountingApi.categories.updateCategory(
        categoryId,
        categoryData,
      );
      const index = categories.value.findIndex((c) => c.id === categoryId);
      if (index !== -1) {
        categories.value[index] = updatedCategory;
      }
      return updatedCategory;
    } catch (err) {
      console.error("更新分类失败:", err);
      error.value = "更新分类失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function deleteCategory(categoryId: number) {
    try {
      loading.value = true;
      error.value = null;
      await accountingApi.categories.deleteCategory(categoryId);
      categories.value = categories.value.filter((c) => c.id !== categoryId);
    } catch (err) {
      console.error("删除分类失败:", err);
      error.value = "删除分类失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 账户相关方法
  async function fetchAccounts(params?: AccountListParams) {
    try {
      loading.value = true;
      error.value = null;
      accounts.value = await accountingApi.accounts.getAccounts(params);
      return accounts.value;
    } catch (err) {
      console.error("获取账户列表失败:", err);
      error.value = "获取账户列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchAccount(accountId: number) {
    try {
      loading.value = true;
      error.value = null;
      return await accountingApi.accounts.getAccount(accountId);
    } catch (err) {
      console.error("获取账户详情失败:", err);
      error.value = "获取账户详情失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createAccount(accountData: AccountCreate) {
    try {
      loading.value = true;
      error.value = null;
      const newAccount =
        await accountingApi.accounts.createAccount(accountData);
      accounts.value.push(newAccount);
      return newAccount;
    } catch (err) {
      console.error("创建账户失败:", err);
      error.value = "创建账户失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateAccount(accountId: number, accountData: AccountUpdate) {
    try {
      loading.value = true;
      error.value = null;
      const updatedAccount = await accountingApi.accounts.updateAccount(
        accountId,
        accountData,
      );
      const index = accounts.value.findIndex((a) => a.id === accountId);
      if (index !== -1) {
        accounts.value[index] = updatedAccount;
      }
      return updatedAccount;
    } catch (err) {
      console.error("更新账户失败:", err);
      error.value = "更新账户失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function deleteAccount(accountId: number) {
    try {
      loading.value = true;
      error.value = null;
      await accountingApi.accounts.deleteAccount(accountId);
      accounts.value = accounts.value.filter((a) => a.id !== accountId);
    } catch (err) {
      console.error("删除账户失败:", err);
      error.value = "删除账户失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 项目相关方法
  async function fetchProjects(params?: {
    is_active?: boolean | null;
    skip?: number;
    limit?: number;
  }) {
    try {
      loading.value = true;
      error.value = null;
      projects.value = await accountingApi.projects.getProjects(params);
      return projects.value;
    } catch (err) {
      console.error("获取项目列表失败:", err);
      error.value = "获取项目列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchProject(projectId: number) {
    try {
      loading.value = true;
      error.value = null;
      return await accountingApi.projects.getProject(projectId);
    } catch (err) {
      console.error("获取项目详情失败:", err);
      error.value = "获取项目详情失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function createProject(projectData: ProjectCreate) {
    try {
      loading.value = true;
      error.value = null;
      const newProject =
        await accountingApi.projects.createProject(projectData);
      projects.value.push(newProject);
      return newProject;
    } catch (err) {
      console.error("创建项目失败:", err);
      error.value = "创建项目失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function updateProject(projectId: number, projectData: ProjectUpdate) {
    try {
      loading.value = true;
      error.value = null;
      const updatedProject = await accountingApi.projects.updateProject(
        projectId,
        projectData,
      );
      const index = projects.value.findIndex((p) => p.id === projectId);
      if (index !== -1) {
        projects.value[index] = updatedProject;
      }
      return updatedProject;
    } catch (err) {
      console.error("更新项目失败:", err);
      error.value = "更新项目失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function deleteProject(projectId: number) {
    try {
      loading.value = true;
      error.value = null;
      await accountingApi.projects.deleteProject(projectId);
      projects.value = projects.value.filter((p) => p.id !== projectId);
    } catch (err) {
      console.error("删除项目失败:", err);
      error.value = "删除项目失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 统计相关方法
  async function fetchStatistics(params?: StatisticsParams) {
    try {
      loading.value = true;
      error.value = null;
      statistics.value =
        await accountingApi.statistics.getTransactionSummary(params);
      return statistics.value;
    } catch (err) {
      console.error("获取统计数据失败:", err);
      error.value = "获取统计数据失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchCategoryStatistics(params?: StatisticsParams) {
    try {
      loading.value = true;
      error.value = null;
      return await accountingApi.statistics.getCategoryStatistics(params);
    } catch (err) {
      console.error("获取分类统计失败:", err);
      error.value = "获取分类统计失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchAccountStatistics(params?: StatisticsParams) {
    try {
      loading.value = true;
      error.value = null;
      return await accountingApi.statistics.getAccountStatistics(params);
    } catch (err) {
      console.error("获取账户统计失败:", err);
      error.value = "获取账户统计失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  async function fetchProjectStatistics(params?: StatisticsParams) {
    try {
      loading.value = true;
      error.value = null;
      return await accountingApi.statistics.getProjectStatistics(params);
    } catch (err) {
      console.error("获取项目统计失败:", err);
      error.value = "获取项目统计失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 初始化数据
  async function initialize() {
    try {
      loading.value = true;
      error.value = null;
      await Promise.all([
        fetchStatistics(),
        fetchCategories(),
        fetchAccounts(),
        fetchProjects(),
      ]);
    } catch (err) {
      console.error("初始化记账数据失败:", err);
      error.value = "初始化记账数据失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 清除错误
  function clearError() {
    error.value = null;
  }

  // 重置状态
  function reset() {
    transactions.value = [];
    categories.value = [];
    accounts.value = [];
    projects.value = [];
    statistics.value = {
      total_income: "0",
      total_expense: "0",
      total_transfer: "0",
      net_income: "0",
      transaction_count: 0,
    };
    error.value = null;
    loading.value = false;
  }

  return {
    // 状态
    transactions,
    categories,
    accounts,
    projects,
    statistics,
    loading,
    error,

    // 计算属性
    incomeTransactions,
    expenseTransactions,
    transferTransactions,
    // incomeCategories,
    // expenseCategories,
    activeAccounts,
    activeProjects,
    totalBalance,

    // 交易方法
    fetchTransactions,
    fetchTransaction,
    createTransaction,
    updateTransaction,
    deleteTransaction,

    // 分类方法
    fetchCategories,
    fetchCategory,
    createCategory,
    updateCategory,
    deleteCategory,

    // 账户方法
    fetchAccounts,
    fetchAccount,
    createAccount,
    updateAccount,
    deleteAccount,

    // 项目方法
    fetchProjects,
    fetchProject,
    createProject,
    updateProject,
    deleteProject,

    // 统计方法
    fetchStatistics,
    fetchCategoryStatistics,
    fetchAccountStatistics,
    fetchProjectStatistics,

    // 工具方法
    initialize,
    clearError,
    reset,
  };
});
